package com.trepadora.mapper;

import java.io.IOException;

import com.fourspaces.couchdb.Database;
import com.fourspaces.couchdb.Document;
import com.fourspaces.couchdb.Session;
import com.fourspaces.couchdb.View;
import com.fourspaces.couchdb.ViewResults;

/**
 * 
 * @author mkorwel
 * 
 */
public class CouchDBMainMapper {

	private static final String DB_HOST = "153.19.192.140";
	private static final int DB_PORT = 5984;
	private static final String DB_NAME = "trepadora";
	
	protected static Database db;

	static {
		Session s = new Session(DB_HOST, DB_PORT);
		db = s.getDatabase(DB_NAME);
	}
	
	protected ViewResults getViewResults(final String viewGroup, final String viewName){
		
		View defView = new View(buildViewDoc(viewGroup, viewName));
		ViewResults viewResults = db.view(defView);
		
		return viewResults;
	}
	
	/**
	 * Getting Document by ID from DB
	 * @param docId
	 * @return
	 */
	public Document getDocumentById(final String docId) {
		
		try {		
			return db.getDocument(docId);
		
		} catch (IOException e) {
			return null;
		}
	}
	
	protected String buildViewDoc(final String viewGroup, final String viewName) {
		
		if (viewGroup != null && viewName != null) {
			return "/_design/" + viewGroup + "/_view/" + viewName;
		} else {
			return null;
		}
	}
	
}
